package search

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"wechat/global"
	"wechat/handle/model"
	"wechat/handle/request"
)

func AddLike(c *gin.Context) {
	var form request.AddLike
	if err := c.ShouldBind(&form); err != nil {
		c.JSONP(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var like model.Like

	if err := like.VeryLike(global.DB, form.UserId, form.MomentId); err != nil {
		like = model.Like{
			UserId:   form.UserId,
			MomentId: form.MomentId,
		}

		err = like.AddLike(global.DB)
		if err != nil {
			return
		}

		global.DB.Model(&model.Moment{}).Where("id=?", form.MomentId).
			Update("count", gorm.Expr("count+1"))
		c.JSONP(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "点赞成功",
		})
		return
	}

	global.DB.Delete(&like, like.ID)
	global.DB.Model(&model.Moment{}).Where("id=?", form.MomentId).
		Update("count", gorm.Expr("count-1"))
	c.JSONP(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "取消点赞成功",
	})
}
